package service

import (
	"context"
	"database/sql"
	"fx_swift_agent/api"
	"fx_swift_agent/internal/model"
	"fx_swift_agent/pkg/code"
	"fx_swift_agent/pkg/global"
	"fx_swift_agent/pkg/internalerrors"
	"fx_swift_agent/pkg/logger"
	"fx_swift_agent/pkg/page"
	"fx_swift_agent/pkg/utils"
	"github.com/gogf/gf/v2/container/gmap"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/golang-module/carbon/v2"
	"github.com/shopspring/decimal"
	"github.com/spf13/cast"
	"time"
)

type IAgentSrv interface {
	// 查询企业帐户申请
	QueryAgentApply(ctx context.Context) (*api.EnterpriseAccountApplyRes, error)
	// 填写企业帐户资料
	UploadEnterpriseInfo(ctx context.Context, req *api.EnterpriseAccountApplyReq) error
	// 获取国家信息
	GetCountryInfo(ctx context.Context) ([]*api.GetCountryRes, error)
	// 资金流水
	CashFlowList(ctx context.Context, req *api.CashFlowListReq) (*page.Collection[*api.CashFlowListRes], error)
	// 首页第一部份
	IndexOne(ctx context.Context) (*api.IndexOneRes, error)
	// 首页开卡趋势
	IndexSecond(ctx context.Context, req *api.IndexSecondReq) ([]*api.IndexSecondRes, error)
	// 首页开卡统计
	IndexThird(ctx context.Context) (*api.IndexThirdReq, error)
	// 首页交易趋势
	IndexFour(ctx context.Context, req *api.IndexFourReq) ([]*api.IndexFourRes, error)
	// 充值申请
	SubmitDiscountOrder(ctx context.Context, req *api.SubmitDiscountOrderReq) error
	// 企业类型
	GetCompanyType(ctx context.Context) ([]*api.GetCompanyTypeRes, error)
	// 发卡国家信息
	GetCardCountryInfo(ctx context.Context) ([]*api.GetCardCountryInfoRes, error)
	// 新增/更新 代理商回调
	OperatorAgentCallBack(ctx context.Context, url string) error
	// 代理商回调显示
	AgentCallBackInfo(ctx context.Context) (string, error)
}

type agentSrv struct {
}

func NewAgentSrv() IAgentSrv {
	return &agentSrv{}
}

// 查询企业帐户申请
func (a *agentSrv) QueryAgentApply(ctx context.Context) (*api.EnterpriseAccountApplyRes, error) {
	var (
		err      error
		applyObj *model.FxEnterpriseAccountApply
		account  string
	)
	account = ctx.Value("Account").(string)
	if err = global.GFDB.Ctx(ctx).Model("fx_enterprise_account_apply").Where("account", account).Scan(&applyObj); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "查询报错")
	}
	if applyObj == nil {
		return nil, internalerrors.New(code.ErrUnknown, "该帐户存在异常")
	}

	return &api.EnterpriseAccountApplyRes{
		CountryId:      applyObj.CountryId,
		Additional:     applyObj.Image,
		CompanyName:    applyObj.CompanyName,
		RegisterCode:   applyObj.RegisterCode,
		CompanyTime:    applyObj.CompanyTime,
		CompanyAddress: applyObj.CompanyAddress,
		CompanyType:    cast.ToInt64(applyObj.CompanyType),
		ContactPerson:  applyObj.ContactPerson,
		Phone:          applyObj.Phone,
		Status:         applyObj.Status,
		RefuseReason:   applyObj.RefuseReason,
	}, nil
}

// 填写企业帐户资料
func (a *agentSrv) UploadEnterpriseInfo(ctx context.Context, req *api.EnterpriseAccountApplyReq) error {
	g.Dump(req)
	var (
		err      error
		result   sql.Result
		applyObj *model.FxEnterpriseAccountApply
		nums     int64
		account  string
	)
	account = ctx.Value("Account").(string)
	if req.Status == "draft" {
		result, err = global.GFDB.Model("fx_enterprise_account_apply").Data(
			g.Map{"country_id": req.CountryId, "company_name": req.CompanyName, "register_code": req.RegisterCode, "company_time": req.CompanyTime,
				"company_type": req.CompanyType, "company_address": req.CompanyAddress, "contact_person": req.ContactPerson,
				"phone": req.Phone, "image": req.Additional}).
			Where("account=?", account).Update()
		if err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, "更新失败")
		}
		nums, err = result.RowsAffected()
		if nums == 0 || err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, "更新失败")
		}
	} else if req.Status == "init" {
		if err = global.GFDB.Ctx(ctx).Model("fx_enterprise_account_apply").
			Where("account", account).Scan(&applyObj); err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, "查询报错")
		}
		if applyObj == nil {
			return internalerrors.New(code.ErrUnknown, "该帐户存在异常")
		}
		result, err = global.GFDB.Model("fx_enterprise_account_apply").Data(
			g.Map{"country_id": req.CountryId, "company_name": req.CompanyName, "register_code": req.RegisterCode, "company_time": req.CompanyTime,
				"company_type": req.CompanyType, "company_address": req.CompanyAddress, "contact_person": req.ContactPerson,
				"phone": req.Phone, "image": req.Additional, "status": req.Status}).
			Where("account=?", account).Update()
		if err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, "更新失败")
		}
		nums, err = result.RowsAffected()
		if nums == 0 || err != nil {
			logger.SugarLogger.Error(err)
			return internalerrors.New(code.ErrUnknown, "更新失败")
		}
	}

	return err
}

// 获取国家信息
func (a *agentSrv) GetCountryInfo(ctx context.Context) ([]*api.GetCountryRes, error) {
	var (
		err         error
		countryList []*model.FxCountry
	)
	if err = global.GFDB.Ctx(ctx).Model("fx_country").Where("1=1").Scan(&countryList); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	result := make([]*api.GetCountryRes, 0)
	for _, value := range countryList {
		result = append(result, &api.GetCountryRes{
			Id: value.ID,
			NameInfo: api.NameInfo{
				ChineseName: value.ChineseName,
				EnglishName: value.EnglishName,
			},
			Status: value.Status,
		})
	}
	return result, err
}

// 发卡国家信息
func (a *agentSrv) GetCardCountryInfo(ctx context.Context) ([]*api.GetCardCountryInfoRes, error) {
	var (
		err         error
		countryList []*model.FxCardCountry
	)
	if err = global.GFDB.Ctx(ctx).Model("fx_card_country").Where("1=1").Scan(&countryList); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	result := make([]*api.GetCardCountryInfoRes, 0)
	for _, value := range countryList {
		result = append(result, &api.GetCardCountryInfoRes{
			Id: value.ID,
			NameInfo: api.NameInfo{
				ChineseName: value.ChineseName,
				EnglishName: value.EnglishName,
			},
			CountryCode: value.CountryCode,
		})
	}
	return result, err
}

// 资金流水
func (a *agentSrv) CashFlowList(ctx context.Context, req *api.CashFlowListReq) (*page.Collection[*api.CashFlowListRes], error) {
	var (
		err        error
		resultList []*api.CashFlowListRes
		total      int
		account    string
	)
	account = ctx.Value("Account").(string)
	collectionDto := &page.Collection[*api.CashFlowListRes]{}
	collectionDto.Page = req.Page
	collectionDto.PageSize = req.PageSize

	mod := global.GFDB.Ctx(ctx).Model("fx_record")
	mod.Fields("discount_order_no,created_at,amount,record_type,`desc` as record_desc,currency,actual_amount,remaining_balance")
	if len(req.DiscountOrderNo) > 0 {
		mod.WhereLike("discount_order_no", "%"+req.DiscountOrderNo+"%")
	}
	if len(req.RecordType) > 0 {
		mod.Where("record_type=?", req.RecordType)
	}
	if len(req.StartTime) > 0 && len(req.EndTime) > 0 {
		mod.Where("created_at >=? and created_at < ?", req.StartTime+" 00:00:00", req.EndTime+" 23:59:59")
	}
	if len(req.SortFields) > 0 && len(req.SortMethod) > 0 {
		mod.Order(req.SortFields + " " + req.SortMethod)
	}
	mod.Where("account=?", account)
	mod.Order("created_at desc")
	mod.Limit(int(page.PageToOffset(req.Page, req.PageSize)), cast.ToInt(req.PageSize))
	err = mod.ScanAndCount(&resultList, &total, false)
	collectionDto.TotalPage = page.GetTotalPage(req.Page, req.PageSize, cast.ToInt64(total))

	if err != nil {
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}

	collectionDto.Total = cast.ToInt64(total)
	collectionDto.List = resultList

	return collectionDto, err
}

// 首页第一部份
func (a *agentSrv) IndexOne(ctx context.Context) (*api.IndexOneRes, error) {
	var (
		err         error
		accountObj  *model.FxAccount
		totalAmount string
		cardNums    int
		account     string
	)
	account = ctx.Value("Account").(string)
	if err = global.GFDB.Ctx(ctx).Model("fx_account").Where("account=? and account_type='agent'", account).
		Scan(&accountObj); err != nil {
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	if accountObj.Balance.Equals(decimal.NewFromFloat(0)) {
		totalAmount = "0"
	} else {
		totalAmount = cast.ToString(accountObj.Balance)
	}

	cardNums, err = global.GFDB.Ctx(ctx).Model("fx_card_info").Where("account=?", account).
		Count()
	if err != nil {
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}

	return &api.IndexOneRes{
		TotalAmount: totalAmount,
		CardNums:    cast.ToString(cardNums),
	}, nil
}

// 首页开卡趋势
func (a *agentSrv) IndexSecond(ctx context.Context, req *api.IndexSecondReq) ([]*api.IndexSecondRes, error) {
	type DbVo struct {
		CardNums       int       `json:"card_nums"`
		CreateCardTime time.Time `json:"create_card_time"`
	}
	var (
		err      error
		sqlDate  string
		sqlStr   string
		dbVoList []DbVo
		result   = make([]*api.IndexSecondRes, 0)
		account  string
	)

	account = ctx.Value("Account").(string)
	if len(req.DateStr) > 0 {
		if req.DateStr == "today" {
			sqlDate = carbon.Now().Format("Y-m-d")
			sqlStr = "select count(1) as card_nums,create_card_time from fx_card_info where account=? and create_card_time like ? group by create_card_time order BY create_card_time asc"
			err = global.GFDB.Raw(sqlStr, account, "%"+sqlDate+"%").Scan(&dbVoList)
		} else if req.DateStr == "day" {
			sqlStr = "select count(1) as card_nums,create_card_time from fx_card_info where account=? and create_card_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) group by create_card_time order BY create_card_time asc"
			err = global.GFDB.Raw(sqlStr, account).Scan(&dbVoList)
		} else if req.DateStr == "weeks" {
			sqlStr = "select count(1) as card_nums,create_card_time from fx_card_info where account=? and create_card_time >= DATE_SUB(CURDATE(), INTERVAL 2 WEEK) group by create_card_time order BY create_card_time asc"
			err = global.GFDB.Raw(sqlStr, account).Scan(&dbVoList)
		} else if req.DateStr == "month" {
			sqlDate = carbon.Now().Format("Y-m")
			sqlStr = "select count(1) as card_nums,create_card_time from fx_card_info where account=? and create_card_time like ? group by create_card_time order BY create_card_time asc"
			err = global.GFDB.Raw(sqlStr, account, "%"+sqlDate+"%").Scan(&dbVoList)
		} else if req.DateStr == "year" {
			sqlDate = carbon.Now().Format("Y")
			sqlStr = "select count(1) as card_nums,create_card_time from fx_card_info where account=? and create_card_time like ? group by create_card_time order BY create_card_time asc"
			err = global.GFDB.Raw(sqlStr, account, "%"+sqlDate+"%").Scan(&dbVoList)
		}
		if err != nil {
			return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
		}
		if len(dbVoList) > 0 {
			maps := gmap.ListMap{}
			for _, value := range dbVoList {
				if !maps.Contains(carbon.Time2Carbon(value.CreateCardTime).ToDateString()) {
					maps.Set(carbon.Time2Carbon(value.CreateCardTime).ToDateString(), value.CardNums)
				} else {
					valueNums := maps.Get(carbon.Time2Carbon(value.CreateCardTime).ToDateString()).(int)
					valueNums += value.CardNums
					maps.Set(carbon.Time2Carbon(value.CreateCardTime).ToDateString(), valueNums)
				}
			}
			maps.Iterator(func(key interface{}, value interface{}) bool {
				result = append(result, &api.IndexSecondRes{
					CardNums:  cast.ToString(value.(int)),
					CreatedAt: key.(string),
				})
				return true
			})
		}
	} else if len(req.StartTime) > 0 && len(req.EndTime) > 0 {
		sqlStr = "select count(1) as card_nums,create_card_time from fx_card_info where account=? and date_format(create_card_time,'%Y-%m-%d') >=? and date_format(create_card_time,'%Y-%m-%d') <= ? group by create_card_time order BY create_card_time asc"
		err = global.GFDB.Raw(sqlStr, account, req.StartTime, req.EndTime).Scan(&dbVoList)
		if err != nil {
			return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
		}
		if len(dbVoList) > 0 {
			maps := gmap.ListMap{}
			for _, value := range dbVoList {
				if !maps.Contains(carbon.Time2Carbon(value.CreateCardTime).ToDateString()) {
					maps.Set(carbon.Time2Carbon(value.CreateCardTime).ToDateString(), value.CardNums)
				} else {
					valueNums := maps.Get(carbon.Time2Carbon(value.CreateCardTime).ToDateString()).(int)
					valueNums += value.CardNums
					maps.Set(carbon.Time2Carbon(value.CreateCardTime).ToDateString(), valueNums)
				}
			}
			maps.Iterator(func(key interface{}, value interface{}) bool {
				result = append(result, &api.IndexSecondRes{
					CardNums:  cast.ToString(value.(int)),
					CreatedAt: key.(string),
				})
				return true
			})
		}
	}
	return result, nil
}

// 首页开卡统计
func (a *agentSrv) IndexThird(ctx context.Context) (*api.IndexThirdReq, error) {
	var (
		err        error
		freezeNums int
		activeNums int
		account    string
	)
	account = ctx.Value("Account").(string)
	freezeNums, err = global.GFDB.Ctx(ctx).Model("fx_card_info").Where("account=? and card_status='0'", account).Count()
	if err != nil {
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	activeNums, err = global.GFDB.Ctx(ctx).Model("fx_card_info").Where("account=? and card_status='1'", account).Count()
	if err != nil {
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	return &api.IndexThirdReq{
		FreezeNums: cast.ToString(freezeNums),
		ActiveNums: cast.ToString(activeNums),
	}, nil
}

// 首页交易趋势
func (a *agentSrv) IndexFour(ctx context.Context, req *api.IndexFourReq) ([]*api.IndexFourRes, error) {
	type DbVo struct {
		TransactionsNums int       `json:"transactions_nums"`
		TradeTime        time.Time `json:"trade_time"`
		Amount           float64   `json:"amount"`
	}
	type IndexFourInfoVo struct {
		TransactionsNums int     `json:"transactions_nums"`
		Amount           float64 `json:"amount"`
	}
	var (
		err      error
		sqlDate  string
		sqlStr   string
		dbVoList []DbVo
		cardList []*model.FxCardInfo
		result   = make([]*api.IndexFourRes, 0)
		cardId   = make([]string, 0)
		account  string
	)

	account = ctx.Value("Account").(string)

	if err = global.GFDB.Ctx(ctx).Model("fx_card_info").Where("account=?", account).
		Scan(&cardList); err != nil {
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	if len(cardList) > 0 {
		for _, value := range cardList {
			cardId = append(cardId, value.CardId)
		}

		if req.DateStr == "today" {
			sqlDate = carbon.Now().Format("Y-m-d")
			sqlStr = "select count(1) as transactions_nums,occur_time as trade_time,local_currency_amt as amount from fx_card_trade_record where card_id in (?) and occur_time like ? and trans_status='APPROVED' group by occur_time,amount order BY occur_time desc"
			err = global.GFDB.Raw(sqlStr, cardId, "%"+sqlDate+"%").Scan(&dbVoList)
		} else if req.DateStr == "day" {
			sqlStr = "select count(1) as transactions_nums,occur_time as trade_time,local_currency_amt as amount from fx_card_trade_record where card_id in (?) and trans_status='APPROVED' and occur_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) group by occur_time,amount order BY occur_time desc"
			err = global.GFDB.Raw(sqlStr, cardId).Scan(&dbVoList)
		} else if req.DateStr == "weeks" {
			sqlStr = "select count(1) as transactions_nums,occur_time as trade_time,local_currency_amt as amount from fx_card_trade_record where card_id in (?) and trans_status='APPROVED' and occur_time >= DATE_SUB(CURDATE(), INTERVAL 2 WEEK) group by occur_time,amount order BY occur_time desc"
			err = global.GFDB.Raw(sqlStr, cardId).Scan(&dbVoList)
		} else if req.DateStr == "month" {
			sqlDate = carbon.Now().Format("Y-m")
			sqlStr = "select count(1) as transactions_nums,occur_time as trade_time,local_currency_amt as amount from fx_card_trade_record where card_id in (?) and trans_status='APPROVED' and occur_time like ? group by occur_time,amount order BY occur_time desc"
			err = global.GFDB.Raw(sqlStr, cardId, "%"+sqlDate+"%").Scan(&dbVoList)
		} else if req.DateStr == "year" {
			sqlDate = carbon.Now().Format("Y")
			sqlStr = "select count(1) as transactions_nums,occur_time as trade_time,local_currency_amt as amount from fx_card_trade_record where card_id in (?) and trans_status='APPROVED' and occur_time like ? group by occur_time,amount order BY occur_time desc"
			err = global.GFDB.Raw(sqlStr, cardId, "%"+sqlDate+"%").Scan(&dbVoList)
		}
		if err != nil {
			return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
		}
		if len(dbVoList) > 0 {
			maps := gmap.ListMap{}
			for _, value := range dbVoList {
				if !maps.Contains(carbon.Time2Carbon(value.TradeTime).ToDateString()) {
					maps.Set(carbon.Time2Carbon(value.TradeTime).ToDateString(), IndexFourInfoVo{
						Amount:           value.Amount,
						TransactionsNums: value.TransactionsNums,
					})
				} else {
					valueObj := maps.Get(carbon.Time2Carbon(value.TradeTime).ToDateString()).(IndexFourInfoVo)
					valueObj.TransactionsNums += value.TransactionsNums
					valueObj.Amount += value.Amount
					maps.Set(carbon.Time2Carbon(value.TradeTime).ToDateString(), valueObj)
				}
			}
			maps.Iterator(func(k interface{}, v interface{}) bool {
				valueObj := v.(IndexFourInfoVo)
				result = append(result, &api.IndexFourRes{
					CreatedAt: k.(string),
					IndexFourInfo: api.IndexFourInfo{
						TransactionsNums: cast.ToString(valueObj.TransactionsNums),
						Amount:           cast.ToString(valueObj.Amount),
					},
				})
				return true
			})
		} else if len(req.StartTime) > 0 && len(req.EndTime) > 0 {
			sqlStr = "select count(1) as transactions_nums,occur_time as trade_time,local_currency_amt as amount from fx_card_trade_record fct left JOIN fx_card_info fci ON fct.card_id = fci.card_id " +
				"where fci.account=? and date_format(fct.occur_time,'%Y-%m-%d') >=? and date_format(fct.occur_time,'%Y-%m-%d') <= ? and fct.trans_status='APPROVED' group by fct.occur_time,amount order BY fct.occur_time desc"
			err = global.GFDB.Raw(sqlStr, account, req.StartTime, req.EndTime).Scan(&dbVoList)
			if err != nil {
				return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
			}
			if len(dbVoList) > 0 {
				maps := gmap.ListMap{}
				for _, value := range dbVoList {
					if !maps.Contains(carbon.Time2Carbon(value.TradeTime).ToDateString()) {
						maps.Set(carbon.Time2Carbon(value.TradeTime).ToDateString(), IndexFourInfoVo{
							Amount:           value.Amount,
							TransactionsNums: value.TransactionsNums,
						})
					} else {
						valueObj := maps.Get(carbon.Time2Carbon(value.TradeTime).ToDateString()).(IndexFourInfoVo)
						valueObj.TransactionsNums += value.TransactionsNums
						valueObj.Amount += value.Amount
						maps.Set(carbon.Time2Carbon(value.TradeTime).ToDateString(), valueObj)
					}
				}
				maps.Iterator(func(k interface{}, v interface{}) bool {
					valueObj := v.(IndexFourInfoVo)
					result = append(result, &api.IndexFourRes{
						CreatedAt: k.(string),
						IndexFourInfo: api.IndexFourInfo{
							TransactionsNums: cast.ToString(valueObj.TransactionsNums),
							Amount:           cast.ToString(valueObj.Amount),
						},
					})
					return true
				})
			}
		}
	}
	return result, nil
}

// 充值申请
func (a *agentSrv) SubmitDiscountOrder(ctx context.Context, req *api.SubmitDiscountOrderReq) error {
	type DbVo struct {
		Account       string  `json:"account"`
		Balance       float64 `json:"balance"`
		ManagementFee float64 `json:"management_fee"`
		CreatedAt     string  `json:"created_at"`
		EffectiveDate string  `json:"effective_date"`
		Status        string  `json:"status"`
	}
	var (
		err           error
		result        sql.Result
		nums          int64
		obj           *model.FxEnterpriseAccountApply
		managementObj *DbVo
		amount        decimal.Decimal
		handFree      decimal.Decimal
		actualAmount  decimal.Decimal
		agentObj      *model.FxAgent
		account       string
		redisResult   *gvar.Var
		managementFee float64
	)
	account = ctx.Value("Account").(string)

	if err = global.GFDB.Model("fx_agent").Where("account=?", account).Scan(&agentObj); err != nil {
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if err = global.GFDB.Model("fx_enterprise_account_apply").Where("account=?", account).Scan(&obj); err != nil {
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if err = global.GFDB.Model("card.fx_agent_management").Where("account=?", account).Scan(&managementObj); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}

	amount = decimal.NewFromFloat(cast.ToFloat64(req.Amount))
	//handFree = amount.Mul(decimal.NewFromFloat(agentObj.Fee))
	handFree = decimal.NewFromFloat(0.00)
	actualAmount = amount

	redisResult, err = g.Redis().Get(nil, account+"_managementFee")
	if err != nil {
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if redisResult.Val() != nil {
		managementFee = redisResult.Float64()
	} else {
		managementFee = managementObj.ManagementFee
	}

	dBCreatedAt := carbon.Parse(managementObj.CreatedAt).ToDateString()
	if carbon.Parse(carbon.Now().ToDateString()).Gt(carbon.Parse(dBCreatedAt).AddDays(3)) {
		//if carbon.Parse("2024-03-02").Gt(carbon.Parse(dBCreatedAt).AddDays(3)) {
		if (managementObj.Status == "outstanding" || managementObj.Status == "noopen") && amount.LessThan(decimal.NewFromFloat(managementFee)) {
			return internalerrors.New(code.ErrUnknown, "您的管理费尚未缴纳，请一并缴纳完成")
		}
	}
	result, err = global.GFDB.Insert(ctx, "fx_discount_order", &model.FxDiscountOrder{
		DiscountOrderNo: utils.GenerateCode32(),
		Account:         account,
		CompanyName:     obj.CompanyName,
		RechargeType:    model.Ordinary,
		Amount:          amount,
		ActualAmount:    actualAmount,
		HandingFree:     handFree,
		Status:          "init",
		TransferImage:   req.TransferImage,
	})
	if err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, "充值申请异常")
	}
	nums, err = result.RowsAffected()
	if err != nil || nums == 0 {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, "充值申请异常")
	}
	return err
}

// 企业类型
func (a *agentSrv) GetCompanyType(ctx context.Context) ([]*api.GetCompanyTypeRes, error) {
	var (
		err             error
		companyTypeList []*model.FxCompanyType
		result          = make([]*api.GetCompanyTypeRes, 0)
	)
	if err = global.GFDB.Ctx(ctx).Model("fx_company_type").Where("1=1").Scan(&companyTypeList); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	for _, value := range companyTypeList {
		result = append(result, &api.GetCompanyTypeRes{
			Id: value.ID,
			NameInfo: api.NameInfo{
				ChineseName: value.ChineseName,
				EnglishName: value.EnglishName,
			},
		})
	}
	return result, err
}

// 新增/更新 代理商回调
func (a *agentSrv) OperatorAgentCallBack(ctx context.Context, url string) error {
	var (
		err              error
		agentCallBackObj *model.FxAgentCallback
		account          string
	)
	account = ctx.Value("Account").(string)

	if err = global.GFDB.Ctx(ctx).Model("fx_agent_callback").
		Where("account=?", account).Scan(&agentCallBackObj); err != nil {
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if agentCallBackObj == nil {
		if _, err = global.GFDB.Ctx(ctx).Model("fx_agent_callback").Insert(&model.FxAgentCallback{
			Account:     account,
			CallBackUrl: url,
		}); err != nil {
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	} else {
		if _, err = global.GFDB.Ctx(ctx).Model("fx_agent_callback").
			Data(g.Map{"call_back_url": url}).Where("account=?", account).Update(); err != nil {
			return internalerrors.New(code.ErrUnknown, err.Error())
		}
	}
	return err
}

// 代理商回调显示
func (a *agentSrv) AgentCallBackInfo(ctx context.Context) (string, error) {
	var (
		err              error
		agentCallBackObj *model.FxAgentCallback
		account          string
	)
	account = ctx.Value("Account").(string)

	if err = global.GFDB.Ctx(ctx).Model("fx_agent_callback").
		Where("account=?", account).Scan(&agentCallBackObj); err != nil {
		return "", internalerrors.New(code.ErrUnknown, err.Error())
	}
	if agentCallBackObj == nil {
		return "", err
	}
	return agentCallBackObj.CallBackUrl, err
}
